package com.coalmine.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coalmine.api.common.ApiDto;
import com.coalmine.api.domain.ApiAlarm;
import com.coalmine.api.domain.ApiConfig;
import com.coalmine.api.domain.ApiDatasource;
import com.coalmine.api.domain.ApiSql;
import com.coalmine.api.mapper.ApiAlarmMapper;
import com.coalmine.api.mapper.ApiConfigMapper;
import com.coalmine.api.mapper.ApiDatasourceMapper;
import com.coalmine.api.mapper.ApiSqlMapper;
import com.coalmine.api.plugin.CachePlugin;
import com.coalmine.api.plugin.PluginManager;
import com.coalmine.api.service.IApiConfigService;
import com.coalmine.api.util.Constants;
import com.coalmine.api.util.JdbcUtil;
import com.coalmine.api.util.PoolManager;
import com.coalmine.api.util.UUIDUtil;
import com.coalmine.common.constant.HttpStatus;
import com.coalmine.common.core.redis.RedisCache;
import com.coalmine.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 尚郑
 * @since 2022-04-01
 */
@Service
@Slf4j
public class ApiConfigServiceImpl extends ServiceImpl<ApiConfigMapper, ApiConfig> implements IApiConfigService {
    @Autowired
    ApiConfigMapper apiConfigMapper;
    @Autowired
    ApiSqlMapper apiSqlMapper;
    @Autowired
    ApiAlarmMapper alarmMapper;
    @Autowired
    ApiDatasourceMapper apiDatasourceMapper;
    @Autowired
    CacheManager cacheManager;
    @Autowired
    private RedisCache redisCache;
    @Value("${datamanage.api.context}")
    String apiContext;

    @Override
    public void add(ApiConfig apiConfig) {
        int size = apiConfigMapper.selectCountByPath(apiConfig.getPath());
        if (size > 0) {
            throw new ServiceException("api已经存在", HttpStatus.ERROR);
        } else {
            apiConfig.setStatus(0);
            String apiId = UUIDUtil.getUUID();
            apiConfig.setId(apiId);
            if (StringUtils.isBlank(apiConfig.getParams())) {
                apiConfig.setParams("[]"); //不能设置null 前端使用会报错
            }
            if (Constants.APP_FORM_URLENCODED.equals(apiConfig.getContentType())) {
                apiConfig.setJsonParam(null);
            }
            apiConfig.setCreateTime(new Date());
            apiConfig.setUpdateBy(apiConfig.getCreateBy());
            apiConfig.setUpdateTime(new Date());
            int row = apiConfigMapper.insert(apiConfig);
            if (row > 0) {
                ApiConfig config = apiConfigMapper.selectByPathOnline(apiConfig.getPath());
                redisCache.setCacheObject(com.coalmine.common.constant.Constants.API_CONFIG_KEY + apiConfig.getPath(), config);
            }
            insertApiSqlAlarm(apiConfig, apiId);
        }
    }

    private  void insertApiSqlAlarm(ApiConfig apiConfig,String apiId){
        apiConfig.getSqlList().stream().forEach(t -> {
            t.setId(UUIDUtil.getUUID());
            t.setApiId(apiId);
            t.setCreateBy(apiConfig.getCreateBy());
            t.setCreateTime(new Date());
            t.setUpdateBy(apiConfig.getUpdateBy());
            t.setUpdateTime(new Date());
            /*String sqlText=t.getSqlText();
            QueryModelInfo queryModelInfo=GetSQLTableName.getAllTableNameBySQL(sqlText);
            List<Object> columnsList=new ArrayList<>();
            if(queryModelInfo!=null){
                List<String> tableNameList=queryModelInfo.getTableName();
                tableNameList.forEach(tb ->{
                    List<JSONObject> allColumnsList=getAllColumns(apiConfig.getDatasourceId(),tb);
                    columnsList.add(allColumnsList);
                });
            }*/
            //t.setJsonResult(JSONArray.toJSONString(t.getJsonResult()));
            apiSqlMapper.insert(t);
        });
        //设置缓存
        List<ApiSql> apiSqls = apiSqlMapper.selectByApiId(apiConfig.getId());
        redisCache.setCacheObject(com.coalmine.common.constant.Constants.API_SQL_KEY + apiConfig.getId(), apiSqls);

        if (apiConfig != null && StringUtils.isNotBlank(apiConfig.getMail())) {
            ApiAlarm alarm = new ApiAlarm();
            alarm.setApiId(apiId);
            alarm.setMail(apiConfig.getMail());
            alarm.setCreateBy(apiConfig.getCreateBy());
            alarm.setCreateTime(new Date());
            alarm.setUpdateBy(apiConfig.getUpdateBy());
            alarm.setUpdateTime(new Date());
            alarmMapper.insert(alarm);
        }
    }


    @Transactional
    public void update(ApiConfig apiConfig) {
        int size = apiConfigMapper.selectCountByPathWhenUpdate(apiConfig.getPath(), apiConfig.getId());
        if (size > 0) {
            throw new ServiceException("api已经存在", HttpStatus.ERROR);
        } else {
            ApiConfig oldConfig = apiConfigMapper.selectById(apiConfig.getId());
            apiConfig.setStatus(0);
            apiConfig.setUpdateTime(new Date());
            apiConfig.setUpdateBy(apiConfig.getUpdateBy());
            if (StringUtils.isBlank(apiConfig.getParams())) {
                apiConfig.setParams("[]"); //不能设置null 前端使用会报错
            }
            if (Constants.APP_FORM_URLENCODED.equals(apiConfig.getContentType())) {
                apiConfig.setJsonParam(null);
            }
            apiConfigMapper.updateById(apiConfig);
            //设置apiConfig缓存
            ApiConfig config = apiConfigMapper.selectByPathOnline(apiConfig.getPath());
            redisCache.setCacheObject(com.coalmine.common.constant.Constants.API_CONFIG_KEY + apiConfig.getPath(), config);
            apiSqlMapper.deleteByApiID(apiConfig.getId());
            alarmMapper.deleteByApiID(apiConfig.getId());
            insertApiSqlAlarm(apiConfig, apiConfig.getId());

            //清除缓存插件对应的所有缓存
            if (oldConfig != null && StringUtils.isNotBlank(oldConfig.getCachePlugin())) {
                try {
                    CachePlugin cachePlugin = PluginManager.getCachePlugin(oldConfig.getCachePlugin());
                    cachePlugin.clean(oldConfig);
                    log.debug("clean cache from old config when update api");
                } catch (Exception e) {
                    log.error("clean cache failed when update api", e);
                }
            }

            cacheManager.getCache("api").evictIfPresent(apiConfig.getPath());
            //如果是集群模式，清除每个apiServer节点内的元数据ehcache缓存
            //metaDataCacheManager.cleanApiMetaCacheIfCluster(apiConfig.getPath());

        }
    }

    @Override
    public void copy(String id) {
        ApiConfig apiConfig = detail(id);
        if (apiConfig != null) {
            String apiId = UUIDUtil.getUUID();
            apiConfig.setId(apiId);
            apiConfig.setPath(apiConfig.getPath() + "_copy");
            apiConfig.setUpdateTime(new Date());
            int row = apiConfigMapper.insert(apiConfig);
            if (row > 0) {
                apiConfig.getSqlList().stream().forEach(t -> {
                    t.setId(UUIDUtil.getUUID());
                    t.setApiId(apiId);
                    apiSqlMapper.insert(t);
                });
            }
        }
    }

    public List<ApiConfig> getAll() {
        QueryWrapper<ApiConfig> queryWrapper = new QueryWrapper();
        List<ApiConfig> list = apiConfigMapper.selectList(queryWrapper.orderByDesc("update_time"));
        //List<ApiConfig> collect = list.stream().sorted(Comparator.comparing(ApiConfig::getUpdateTime).reversed()).collect(Collectors.toList());
        return list;
    }


    public ApiConfig detail(String id) {
        ApiConfig apiConfig = apiConfigMapper.selectById(id);
        List<ApiSql> list = apiSqlMapper.selectByApiId(apiConfig.getId());
        apiConfig.setSqlList(list);
        String mail = alarmMapper.selectMailByApiId(apiConfig.getId());
        apiConfig.setMail(mail);
        return apiConfig;
    }

    @Override
    public List<ApiConfig> search(String keyword, String field, String groupId) {
        if (StringUtils.isNotBlank(keyword)) {
            keyword = "%" + keyword + "%";
        }
        return apiConfigMapper.selectByKeyword(keyword, field, groupId);
    }

    @Override
    public List<Map> searchResource(String name, String apiId, String groupId) {
        if (StringUtils.isNotBlank(name)) {
            name = "%" + name + "%";
        }
        return apiConfigMapper.searchResource(name, apiId, groupId);
    }

    @Override
    public List<Map> getByGroupId(String groupId) {
        return apiConfigMapper.getByGroupId(groupId);
    }

    @Override
    public List<ApiSql> getSqlByConfigId(String id) {
        return apiSqlMapper.selectByApiId(id);
    }

    @Override
    public String searchResourceCount() {
        return apiConfigMapper.searchResourceCount();
    }

    @Override
    public List<ApiConfig> listByGroupIds(List<String> groupIds) {
        return apiConfigMapper.listByGroupIds(groupIds);
    }

    @Transactional
    public Integer delete(String id) {
        ApiConfig oldConfig = apiConfigMapper.selectById(id);
        if (oldConfig.getStatus() == 1) {
            throw new ServiceException("api已上线，不能删除", HttpStatus.ERROR);
        }
        //清除所有缓存
        if (StringUtils.isNotBlank(oldConfig.getCachePlugin())) {
            try {
                CachePlugin cachePlugin = PluginManager.getCachePlugin(oldConfig.getCachePlugin());
                cachePlugin.clean(oldConfig);
                log.debug("delete api then clean cache");
            } catch (Exception e) {
                log.error("clean cache failed when delete api", e);
            }
        }
        cacheManager.getCache("api").evictIfPresent(oldConfig.getPath());
        //删除apiSQL缓存
        redisCache.deleteObject(com.coalmine.common.constant.Constants.API_SQL_KEY + id);
        apiSqlMapper.deleteByApiID(id);
        alarmMapper.deleteByApiID(id);
        //删除apiConfig缓存
        redisCache.deleteObject(com.coalmine.common.constant.Constants.API_CONFIG_KEY + oldConfig.getPath());
        return apiConfigMapper.deleteById(id);
    }

    @Override
    public String getPath(String id) {
        return apiConfigMapper.selectById(id).getPath();
    }

    public void online(String id, String path) {
        ApiConfig apiConfig = apiConfigMapper.selectById(id);
        apiConfig.setStatus(1);
        apiConfigMapper.updateById(apiConfig);
        //设置apiConfig缓存
        ApiConfig config = apiConfigMapper.selectByPathOnline(apiConfig.getPath());
        redisCache.setCacheObject(com.coalmine.common.constant.Constants.API_CONFIG_KEY + apiConfig.getPath(), config);
    }

    //    @CacheEvict(value = "api", key = "#path")
    public void offline(String id, String path) {
        ApiConfig apiConfig = apiConfigMapper.selectById(id);
        apiConfig.setStatus(0);
        apiConfigMapper.updateById(apiConfig);
        //设置apiConfig缓存
        ApiConfig config = apiConfigMapper.selectByPathOnline(apiConfig.getPath());
        redisCache.setCacheObject(com.coalmine.common.constant.Constants.API_CONFIG_KEY + apiConfig.getPath(), config);
        cacheManager.getCache("api").evictIfPresent(path);

        if (StringUtils.isNotBlank(apiConfig.getCachePlugin())) {
            try {
                CachePlugin cachePlugin = PluginManager.getCachePlugin(apiConfig.getCachePlugin());
                cachePlugin.clean(apiConfig);
                log.debug("offline api then clean cache");
            } catch (Exception e) {
                log.error("clean cache error", e);
            }
        }
        //如果是集群模式，清除每个apiServer节点内的元数据ehcache缓存
        //metaDataCacheManager.cleanApiMetaCacheIfCluster(path);
    }

    //@Cacheable(value = "api", key = "#path", unless = "#result == null")
    public ApiConfig getConfig(String path) {
        //log.info("get api config from db");
        ApiConfig apiConfig = redisCache.getCacheObject(com.coalmine.common.constant.Constants.API_CONFIG_KEY + path);
        if (apiConfig == null) {
            apiConfig = apiConfigMapper.selectByPathOnline(path);
            redisCache.setCacheObject(com.coalmine.common.constant.Constants.API_CONFIG_KEY + path, apiConfig, 4, TimeUnit.HOURS);
        }
        if (apiConfig != null) {
            // List<ApiSql> apiSqls = apiSqlMapper.selectByApiId(apiConfig.getId());
            List<ApiSql> apiSqls = redisCache.getCacheObject(com.coalmine.common.constant.Constants.API_SQL_KEY + apiConfig.getId());
            if (apiSqls == null || apiSqls.isEmpty()) {
                apiSqls = apiSqlMapper.selectByApiId(apiConfig.getId());
                redisCache.setCacheObject(com.coalmine.common.constant.Constants.API_SQL_KEY + apiConfig.getId(), apiSqls, 4, TimeUnit.HOURS);
            }
            apiConfig.setSqlList(apiSqls);
            //String mail = alarmMapper.selectMailByApiId(apiConfig.getId());
            //apiConfig.setMail(mail);
        }
        return apiConfig;
    }
    public JSONArray getAllDetail() {
        JSONArray array = new JSONArray();
        List<ApiDto> list = apiConfigMapper.getAllDetail();
        if (list!=null&&list.size()>0){
            Map<String, List<ApiDto>> map = list.stream().collect(Collectors.groupingBy(ApiDto::getGroupName));
            map.keySet().forEach(t -> {
                JSONObject jo = new JSONObject();
                jo.put("name", t);
                List<ApiDto> apiDtos = map.get(t);
                jo.put("children", apiDtos);
                array.add(jo);
            });
        }
        return array;
    }

    public String apiDocs(List<String> ids) {
        StringBuffer temp = new StringBuffer("# 接口文档\n---\n");
        List<ApiConfig> list = apiConfigMapper.selectBatchIds(ids);
        //获取所有api_id的List<ApiSql>的集合
        Map<String, List<ApiSql>> apiSqlMap = getStringApiSqlListMap();
        //获取所有ApiDatasource的集合
        Map<String, ApiDatasource> apiDatasourceMap = getStringApiDatasourceMap();
        try {
            list.stream().forEach(t -> {
                temp.append("## ").append(t.getName()).append("\n- 接口地址： /dm/").append(t.getPath())
                        .append("\n- 接口备注：").append(t.getNote());
                temp.append("\n- Content-Type：").append(t.getContentType());

                temp.append("\n- 请求参数：");
                if (Constants.APP_FORM_URLENCODED.equalsIgnoreCase(t.getContentType())) {
                    String params = t.getParams();
                    JSONArray array = JSON.parseArray(params);

                    if (array.size() > 0) {
                        StringBuffer buffer = new StringBuffer();
                        buffer.append("\n\n| 参数名称 | 参数类型 | 参数说明 |\n");
                        buffer.append("| :----: | :----: | :----: |\n");

                        for (int i = 0; i < array.size(); i++) {
                            JSONObject jsonObject = array.getJSONObject(i);
                            String name = jsonObject.getString("name");
                            String type = jsonObject.getString("type");
                            if (type.startsWith("Array")) {
                                type = type.substring(6, type.length() - 1) + "数组";
                            }
                            String note = jsonObject.getString("note");
                            buffer.append("|").append(name).append("|").append(type).append("|").append(note).append("|\n");
                        }

                        temp.append(buffer);
                    } else {
                        temp.append("无参数\n");
                    }
                } else if (Constants.APP_JSON.equalsIgnoreCase(t.getContentType())) {
                    temp.append("\n```json\n").append(t.getJsonParam()).append("\n```\n");
                }
                temp.append("\n---\n");
                //返回dtd
                temp.append("\n- 返回结果示例(含所有字段)：");
                //返回dtd,从map中获取 List<ApiSql>和ApiDatasource
                List<ApiSql> apiSqlList = apiSqlMap.get(t.getId());
                //List<List<Map<String, String>>> apiResultList = new ArrayList<>();
                // List<Map<String,String>> apiResult=new ArrayList<>();
                //ApiDatasource apiDatasource = apiDatasourceMapper.selectById(t.getDatasourceId());
                ApiDatasource apiDatasource = apiDatasourceMap.get(t.getDatasourceId());
                //System.out.println("function e0========="+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(Calendar.getInstance().getTime()));
                for (ApiSql apiSql : apiSqlList) {
                    try {
                        List<Map<String, String>> apiResult = JdbcUtil.getSqlResult(apiDatasource,
                                apiSql.getSqlText(), null);
                        // apiResultList.add(apiResult);
                        if (!apiResult.isEmpty()) {
                            StringBuffer buffer = new StringBuffer();
                            buffer.append("\n\n| 字段列名 | 字段类型 | 字段备注 |\n");
                            buffer.append("| :----: | :----: | :----: |\n");
                            for (Map<String, String> resultSetMap : apiResult) {
//                             String columnName = resultSetMap.get("columnName");
//                             String columnType = resultSetMap.get("columnType");
//                             String remark = resultSetMap.get("remark");
                                String columnName = resultSetMap.get("fieldTypeName");
                                String columnType = resultSetMap.get("fieldJavaTypeName");
                                String remark = resultSetMap.get("columnRemark");
                                buffer.append("|").append(columnName).append("|").append(columnType).append("|")
                                        .append(remark).append("|\n");
                            }
                            buffer.append("\n\n");
                            temp.append(buffer);
                        }
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            });
            temp.append("\n---\n");
            temp.append("\n导出日期：" + DateUtil.now());
            return temp.toString();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出API文档失败", e.getMessage());
            throw new ServiceException("导出API文档失败", HttpStatus.ERROR);
        }
    }

    public List<Map<String, Object>> apiDocx(List<String> ids) {
        List<ApiConfig> list = apiConfigMapper.selectBatchIds(ids);
        //获取所有api_id的List<ApiSql>的集合
        Map<String, List<ApiSql>> apiSqlMap = getStringApiSqlListMap();
        //获取所有ApiDatasource的集合
        Map<String, ApiDatasource> apiDatasourceMap = getStringApiDatasourceMap();
        List<Map<String, Object>> tList = new ArrayList<>();
        Map<String, Object> tMap;
        try {
            for (ApiConfig apiConfig : list) {
                tMap = new HashMap<>();
                //组装接口基本信息数据
                tMap.put("name", apiConfig.getName());//接口名称
                tMap.put("path", apiContext + "/" + apiConfig.getPath());//请求路径
                tMap.put("contentType", apiConfig.getContentType());//Content-Type
                tMap.put("remark", apiConfig.getNote());//接口备注
                //组装表格参数说明
                String params = apiConfig.getParams();
                JSONArray array = JSON.parseArray(params);
                StringBuffer paramExample = new StringBuffer("?");
                List<Map<String, Object>> detailList = new ArrayList<>();
                if (array.size() > 0) {
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        String name = jsonObject.getString("name");
                        String isMust = jsonObject.getString("isMust");
                        String type = jsonObject.getString("type");
                        if (type.startsWith("Array")) {
                            type = type.substring(6, type.length() - 1) + "数组";
                        }
                        String note = jsonObject.getString("note");
                        Map<String, Object> detailMap = new HashMap<>();
                        detailMap.put("name", name);//参数名称
                        detailMap.put("type", type);//参数类型
                        detailMap.put("isMust", isMust);//是否必填
                        detailMap.put("note", note);//参数备注
                        if (i <= 3) {
                            paramExample.append(name).append("=").append("xxx").append("&");
                        }
                        detailList.add(detailMap);
                    }
                }
                if (Constants.APP_FORM_URLENCODED.equalsIgnoreCase(apiConfig.getContentType())) {
                    tMap.put("requestType", "GET");//请求方式
                    String paramEx = "[]".equals(apiConfig.getParams()) == true ? "无参数"
                            : paramExample.deleteCharAt(paramExample.length() - 1).toString();
                    tMap.put("paramExample", paramEx);//参数示例
                } else {
                    tMap.put("requestType", "POST");
                    String paramEx = StringUtils.isBlank(apiConfig.getJsonParam()) == true ? "无参数" : apiConfig.getJsonParam();
                    tMap.put("paramExample", paramEx);//参数示例
                }

                //组装返回字段表格说明
                List<ApiSql> apiSqlList = apiSqlMap.get(apiConfig.getId());
                ApiDatasource apiDatasource = apiDatasourceMap.get(apiConfig.getDatasourceId());
                List<Map<String, Object>> resultList = new ArrayList<>();
                for (ApiSql apiSql : apiSqlList) {
                    try {
                        List<Map<String, String>> apiResult = JdbcUtil.getSqlResult(apiDatasource,
                                apiSql.getSqlText(), null);
                        if (!apiResult.isEmpty()) {
                            for (Map<String, String> resultSetMap : apiResult) {
                                Map<String, Object> resultMap = new HashMap<>();
                                String columnName = resultSetMap.get("fieldTypeName");
                                String columnType = resultSetMap.get("fieldJavaTypeName");
                                String remark = resultSetMap.get("columnRemark");
                                resultMap.put("fieldTypeName", columnName);//返回字段名称
                                resultMap.put("fieldJavaTypeName", columnType);//返回字段类型
                                resultMap.put("columnRemark", remark);//返回字段说明
                                resultList.add(resultMap);
                            }
                        }
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
                tMap.put("detailList", detailList);
                tMap.put("resultList", resultList);
                tList.add(tMap);
            }
            return tList;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出接口docx失败", e.getMessage());
            throw new ServiceException("导出接口docx失败", HttpStatus.ERROR);
        }
    }


    //获取所有api_id的List<ApiSql>并转换成map，map中的key为api_id,value为api_id对应ApiSql的list集合
    private Map<String, List<ApiSql>> getStringApiSqlListMap() {
        Map<String, List<ApiSql>> apiSqlMap = new HashMap<>();
        List<ApiSql> apiSqlLis = apiSqlMapper.selectAllApiSql();
        for (ApiSql a : apiSqlLis) {
            if (apiSqlMap.get(a.getApiId()) != null) {
                System.out.println(apiSqlMap.get(a.getApiId()));
                List<ApiSql> has = apiSqlMap.get(a.getApiId());
                has.add(a);
                apiSqlMap.put(a.getApiId(), has);
            }
            if (apiSqlMap.get(a.getApiId()) == null) {
                List<ApiSql> inList = new ArrayList<>();
                inList.add(a);
                apiSqlMap.put(a.getApiId(), inList);
            }
        }

        //List<ApiSql> x = apiSqlMap.get("cc37a359ca6b46fc9be9150a037b0b31");
        //System.out.println(x.size());

        return apiSqlMap;
    }

    //获取所有ApiDatasource并转换成map，map中的key为id,value为id对应的ApiDatasource
    private Map<String, ApiDatasource> getStringApiDatasourceMap() {
        QueryWrapper<ApiDatasource> query = new QueryWrapper<ApiDatasource>();
        List<ApiDatasource> listApiDatasource = apiDatasourceMapper.selectList(query.orderByDesc("update_time"));
        Map<String,ApiDatasource> apiDatasourceMap= new HashMap<>();
        for (ApiDatasource s:
                listApiDatasource) {
            apiDatasourceMap.put(s.getId(),s);
        }
        return apiDatasourceMap;
    }


    public JSONObject selectBatch(List<String> ids) {
        List<ApiConfig> list = apiConfigMapper.selectBatchIds(ids);
        List<ApiSql> sqls = apiSqlMapper.selectByApiIds(ids);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("api", list);
        jsonObject.put("sql", sqls);
        return jsonObject;
    }
    @Transactional
    public void insertBatch(List<ApiConfig> configs, List<ApiSql> sqls, String userName) {
        try {
            configs.stream().forEach(t -> {
                t.setCreateBy(userName);
                t.setUpdateBy(userName);
                t.setCreateTime(new Date());
                t.setUpdateTime(new Date());
                t.setStatus(0);
                apiConfigMapper.insert(t);

            });
            sqls.stream().forEach(t ->{
                t.setCreateBy(userName);
                t.setUpdateBy(userName);
                t.setCreateTime(new Date());
                t.setUpdateTime(new Date());
                apiSqlMapper.insert(t);
            });
        }
        catch (Exception e) {
            log.error("API导入失败",e.getMessage());
            throw new ServiceException("API导入失败", HttpStatus.ERROR);
        }
    }

    @Override
    public List<JSONObject> getAllColumns(String sourceId, String table){
        ApiDatasource apiDatasource = apiDatasourceMapper.selectById(sourceId);
        List<JSONObject> columns=new ArrayList<>();
        try {
          DruidPooledConnection connection = PoolManager.getPooledConnection(apiDatasource);
          columns = JdbcUtil.getRDBMSColumnsPropertie(connection, apiDatasource.getType(), table);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return columns;
    }

    /**
     * 查询最新资源默认发布的前五个
     * @return
     */
    @Override
    public List<Map> getNewestList() {
        List<Map> newResList = apiConfigMapper.getNewestList();
        if (CollUtil.isEmpty(newResList)){
            return new ArrayList<>();
        }
        return newResList;
    }

    /**
     * 查询最热资源默认发布的前五个
     * @return
     */
    @Override
    public List<Map> getHotList() {
        List<Map> hotResList = apiConfigMapper.getHotList();
        if (CollUtil.isEmpty(hotResList)){
            return new ArrayList<>();
        }
        return hotResList;
    }


}
